package com.lucien.framework.web.qiniu;

import com.google.gson.Gson;
import com.lucien.framework.config.CloudStorageConfig;
import com.lucien.framework.exception.GlobalException;
import com.lucien.system.service.SysUserService;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;

/**
 * @Author: Lucien
 * @Description: 七牛云上传实现类
 * @Date: Created in 2021/5/5
 */
@Component
public class UploadServiceImpl extends UploadService {

    @Autowired
    private SysUserService userService;

    /**
     * 七牛文件上传管理器
     */
    private UploadManager uploadManager;

    /**
     * 七牛认证管理
     */
    private Auth auth;

    private String token;

    public UploadServiceImpl(CloudStorageConfig config) {
        this.CLOUD_STORAGE_CONFIG = config;
        init();
    }

    private void init() {
        //构造一个带指定Zone对象的配置类  ???Zone.zone0需要根据主机选择
        uploadManager = new UploadManager(new Configuration(Zone.zone2()));

        auth = Auth.create(CLOUD_STORAGE_CONFIG.getQiniuAccessKey(), CLOUD_STORAGE_CONFIG.getQiniuSecretKey());
        // 根据命名空间生成的上传token
        token = auth.uploadToken(CLOUD_STORAGE_CONFIG.getQiniuBucketName());
    }

    /**
     * 用户上传头像
     * @param file
     * @param path
     * @return 得到的外链地址
     */
    @Override
    public String uploadImg(FileInputStream file, String path) {
        try {
            Response response = uploadManager.put(file, path, token, null, null);
            if (!response.isOK()) {
                throw new GlobalException("上传七牛云错误：" + response.toString());
            }
            DefaultPutRet defaultPutRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

            //resultPath是获得到的外链地址,通过这个地址可以直接打开图片
            String resultPath = CLOUD_STORAGE_CONFIG.getQiniuDomain() + "/" + defaultPutRet.key;

            return resultPath;
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }
}
